import {
  observable,
  action
} from 'mobx';
import {
  WeaTools
} from 'ecCom';
import isEmpty from 'lodash/isEmpty';
import {
  validate,
  getFormParamValue
} from '../util'
import * as PublicFunc from '../util/pulic-func';
import {
  WeaForm
} from 'comsMobx';
import {
  message,
  Modal
} from 'antd';
import * as api from '../apis/card';
import {
	i18n
} from '../public/i18n';
import {
  indexOf
} from 'lodash';
import * as mobx from 'mobx';
import isArray from 'lodash/isArray';
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const toJS = mobx.toJS;
const confirm = Modal.confirm;

export class HrmCardInfo4Formal {
  loading = false;
  @observable isSelf = false;
  @observable modelItems = []
  @observable infoGroup = []
  @observable infoGroup2 = []
  @observable imgSrc = null
  @observable sendButtons = []
  @observable accountInfo = []
  @observable showSQR = false
  @observable showBigImg = false
  @observable showAccountInfo = false
  @observable isEditor = false
  @observable buttons = {}
  @observable hideBelongto = true
  @observable rightMenus = []
  @observable conditioninfo = []
  @observable form = new WeaForm()
  @observable QRCodeOptions = {};
  @observable hasQRCode = false;

  @observable remarkInfo = {}
  @observable tagInfo = {}

  @observable visibleWeiXin = false;

  hrmId = undefined;
  
  validate;

  @action
  updateVisibleWeiXin(bool) {
    this.visibleWeiXin = bool;
  }
  
  updateHideBelongto(bool) {
    this.hideBelongto = bool;
  }

  @action
  updateShowAccountInfo(bool) {
    this.showAccountInfo = bool;
  }

  @action
  updateShowBigImg(bool) {
    this.showBigImg = bool;
  }

  @action
  updateIsEditor(bool) {
    this.isEditor = bool || false;
  }

  @action
  updateShowSQR(bool) {
    this.showSQR = bool;
  }

  format(datas) {
    let infoGroup = []; //信息组
    let imgSrc = null; //人员照片
    let sendButtons = [];
    let accountInfo = [];
    let hrmInfo = [];
    datas && datas.forEach(d => {
      if (d.id == 'item1') {
        hrmInfo = d.items;
      }
      if (d.id == 'item2') {
        d.items.forEach(d2 => {
          d2.name == 'resourceimageid' && (imgSrc = d2.value)
          isArray(d2.options) && (sendButtons = d2.options);
          d2.accountinfo && (accountInfo = d2.accountinfo)
        })
      }
      //old
      if (d.id == 'item4' || d.id == 'item5') infoGroup.push(d);
      //专长介绍-modify by sunjun
      if (d.id === 'item6') {
        this.remarkInfo = d.items[0];
        this.tagInfo = d.items[1];
      }
    })
    this.infoGroup = infoGroup;
    this.imgSrc = imgSrc;
    this.sendButtons = sendButtons;
    this.accountInfo = accountInfo;
  }

  @action
  edit(hrmId) {
    WeaTools.callApi('/api/hrm/resource/getResourceCard', 'GET', {
      operation: 'getResourceBaseView',
      //isFormal: '1',
      is_multilang_set:true,
      viewattr: 2,
      id: hrmId
    }).then((data) => {
      this.form = new WeaForm();
      this.form.initFormFields(data.result.conditions);
      let resourceimageid = getFormParamValue(data.result.conditions, 'resourceimageid');
      this.form.updateFields({
        resourceimageid: {
          name: 'resourceimageid',
          value: resourceimageid
        }
      });
      const params = this.form.getFormParams();
      this.conditioninfo = data.result.conditions;
      this.hrmId = data.result.id;
      this.editcontact = data.result.editcontact;
      let accounttype = params.accounttype || '0'
      this.hideBelongto = accounttype == '0'
    })
    this.isEditor = true;
  }

  saveEditCard(cb) {
    if(this.loading)
      return;
    this.loading = true;
    let __this = this;
    const fieldParams = this.form.getFormParams();
    const conditioninfo = this.conditioninfo;
    const editcontact = this.editcontact;
    const hrmId = this.hrmId;
    const lastname = fieldParams.lastname || '';
    const workcode = fieldParams.workcode || '';
    const managerid = fieldParams.managerid || '';
    const accounttype = fieldParams.accounttype || '';
    const belongto = fieldParams.belongto || '';
    const email = fieldParams.email || '';
    const mobile = fieldParams.mobile || '';
    const mobilecall = fieldParams.mobilecall||'';

    if (!PublicFunc.chkMail(email)){
      this.loading = false;
      return false;
    };
    if (validate(conditioninfo, fieldParams)) {
      //选次账号后，必须选主账号
      if (accounttype && accounttype == 1) {
        if (!belongto || belongto == '') {
          message.warning(getLabel('386411',"主账号未填写"));
          __this.loading = false;
          return;
        }
      }
      if (managerid == '' && (!editcontact || editcontact == '')) {
        confirm({
          title: i18n.confirm.systemhints(),
          content:getLabel('16072',"此员工还没有输入直接上级，确定不输入吗？"),
          onOk() {
            WeaTools.callApi('/api/hrm/resource/hrmResourceCheck', 'GET', { ...{
                id: hrmId,
                lastname,
                workcode,
                managerid,
                mobile,
                mobilecall
              }
            }).
            then(data => {
              if (data.status == '-1') {
                if (data.messagetype == 'confirm') {
                  confirm({
                    title: i18n.confirm.systemhints(),
                    content: data.message,
                    onOk() {
                      __this.doSave(cb);
                    },
                    onCancel() {},
                  });
                } else {
                  message.warning(data.message);
                  __this.loading = false;
                }
              } else {
                __this.doSave(cb);
              }
            }, error => {
              message.warning(error.message);
              __this.loading = false;
            })
          },
          onCancel() {
            __this.loading = false;
          },
        });
      } else {
        WeaTools.callApi('/api/hrm/resource/hrmResourceCheck', 'GET', { ...{
            id: hrmId,
            lastname,
            workcode,
            managerid,
            mobile,
            mobilecall
          }
        }).
        then(data => {
          if (data.status == '-1') {
            if (data.messagetype == 'confirm') {
              confirm({
                title: i18n.confirm.systemhints(),
                content: data.message,
                onOk() {
                  __this.doSave(cb);
                },
                onCancel() {
                  __this.loading = false;
                },
              });
            } else {
              message.warning(data.message);
              __this.loading = false;
            }
          } else {
            __this.doSave(cb);
          }
        }, error => {
          message.warning(error.message);
          __this.loading = false;
        })
      }
    }else{
      __this.loading = false;
    }
  }

  doSave(cb) {
    const fieldParams = this.form.getFormParams();
    const editcontact = this.editcontact;
    const hrmId = this.hrmId;
    WeaTools.callApi('/api/hrm/resource/editResource', 'POST', { ...{
        operation: 'editresourcebasicinfo',
        id: hrmId,
        //isFormal: '1',
        editcontact
      },
      ...fieldParams
    }).
    then(data => {
      if (data.status == '1') {
        message.success(i18n.message.saveSuccess());
        this.isEditor = false;
        this.getData(hrmId);
        cb();
      } else {
        message.warning(data.message);
      }
      this.loading = false;
    }, error => {
      message.warning(error.message);
      this.loading = false;
    })
  }

  @action
  getRightMenu(hrmId) {
    WeaTools.callApi('/api/hrm/resource/getRightMenu', 'GET', {
      id: hrmId
    }).then(data => {
      this.rightMenus = data.rightMenus;
    })
  }

  @action
  qrcode(hrmId) {
    WeaTools.callApi('/api/hrm/resource/getQRCode', 'GET', {
      id: hrmId
    }).then(obj => {
      this.QRCodeOptions = obj.options;
    }).catch(err => {
      message.error(err);
    })
  }

  @action
  getData(hrmId) {
    this.hrmId = hrmId;
    this.hideBelongto = true;
    Promise.all([
      WeaTools.callApi('/api/hrm/resource4formal/getResourceCard', 'GET', {
        operation: 'getResourceBaseView',
        id: hrmId,
        noLoadData: 1
      }),
      WeaTools.callApi('/api/hrm/resource4formal/getResourceCard', 'GET', {
        operation: 'getResourceBaseView',
        id: hrmId,
        cmd: 'getResourceBaseData',
        noLoadData: 1
      }),
      WeaTools.callApi('/api/hrm/resource/getHrmResourceItem', 'GET', {
        id: hrmId,
        noLoadData: 1
      })
    ]).then(res => {
      this.isSelf = res[0].isSelf || false;
      this.format(res[0].result);
      this.infoGroup2 = res[1].result;
      this.buttons = res[0].buttons;
      this.modelItems = res[2];
      WeaTools.callApi('/api/hrm/resource4formal/getResourceCard', 'GET', {
          operation: 'getResourceBaseView',
          id: hrmId
        }).then(datas => {
          this.format(datas.result);
          this.validate = datas.validate;
        }),
        WeaTools.callApi('/api/hrm/resource4formal/getResourceCard', 'GET', {
          operation: 'getResourceBaseView',
          id: hrmId,
          cmd: 'getResourceBaseData'
        }).then(datas => {
          this.infoGroup2 = datas.result;
        })
      WeaTools.callApi('/api/hrm/resource/getHrmResourceItem', 'GET', {
        id: hrmId
      }).then(datas => {
        this.modelItems = datas;
      })
      this.qrcode(hrmId);
    })
  }

  @action saveRemark = (params) => {
    api.saveRemark(params).then(data => {
      if (data.status === '1') {
        this.remarkInfo.value = params.remark;
        message.success(i18n.message.saveSuccess());
      } else
        message.error(data.message);
    }, error => {

    })
  }

  @action saveTag = (dom) => {
    let params = {
      tag: dom.value
    }
    if (params.tag === '' || params.tag.trim().length === 0)
      return;
    this.hrmId != '' && Object.assign(params, {
      id: this.hrmId
    })

    const arr = toJS(this.tagInfo.value);
    if (indexOf(arr, params.tag) >= 0) {
      message.error(getLabel('386438',"已存在相同标签"));
      dom.value = '';
    } else {
      api.saveTag(params).then(data => {
        if (data.status === '1') {
          dom.value = '';
          message.success(i18n.message.saveSuccess());
          this.tagInfo.value.push(params.tag);
        } else
          message.error(data.message);
      }, error => {

      })
    }
  }

  @action delTag = (params) => {
    this.hrmId != '' && Object.assign(params, {
      id: this.hrmId
    })
    api.delTag(params).then(data => {
      if (data.status === '1') {
        message.success(i18n.message.saveSuccess());
        this.tagInfo.value.splice(indexOf(this.tagInfo.value, params.tag), 1);
      } else
        message.error(data.message);
    }, error => {

    })
  }
}